<?php

namespace App\Models\Bureau;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class WxBureauGroup extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_bureau_group';
    public $timestamps = false;

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {

        });

        static::created(function ($model) {
            if($model->type == 1){
                // 1个队
                $team = new WxClubTeam();
                $team->type = 2;
                $team->user_id = $model->user_id;
                $team->bureau_id = $model->bureau_id;
                $team->club_id = $model->club_id;
                $team->group_id = $model->id;
                $team->members_num = 0;
                $team->members_limit = $model->total_people;
                $team->save();
            }else if($model->type == 2 || $model->type == 3){
                // 多个队
                if($model->num_teams > 0){
                    for($i = 0; $i < $model->num_teams; $i++){
                        $team = new WxClubTeam();
                        $team->type = 2;
                        $team->user_id = $model->user_id;
                        $team->bureau_id = $model->bureau_id;
                        $team->club_id = $model->club_id;
                        $team->group_id = $model->id;
                        $team->members_num = 0;
                        $team->members_limit = $model->people_per_team;
                        $team->save();
                    }
                }
            }
        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            WxClubTeam::where('type', 2)->where('group_id', $model->id)->update([
                'members_limit'=>$model->type == 1 ? $model->total_people : $model->people_per_team,
                'bureau_id' => $model->bureau_id,
                'club_id' => $model->club_id,
                'user_id' => $model->user_id,
            ]);
//            $original = $model->original;
//            $changes = $model->getChanges();
//
//            // 对比更新前后的字段
//            foreach ($changes as $key => $value) {
//                $originalValue = $original[$key];
//                if($key == 'total_people') {
//
//                }
//            }
        });

        static::deleted(function ($model) {
            WxClubTeam::where('type', 2)->where('group_id', $model->id)->delete();
        });
    }

}
